<template>
  <div>
    <el-row :gutter="30">
      <el-col :span="12">
        <el-tabs v-model="activeName1">
          <el-tab-pane label="角色设定" name="1">
            <el-table
              v-loading="loading"
              :data="roleTableData"
              border
              style="width: 100%"
              highlight-current-row
              @row-click="handleCurrentChange"
              @selection-change="handleSelectionChange"
            >
              <el-table-column
                align="center"
                type="selection"
                width="55"
              />
              <el-table-column :label="$t('角色名称')" prop="roleName" />
              <el-table-column :label="$t('角色标识')" prop="roleKey" />
            </el-table>
            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
          </el-tab-pane>
        </el-tabs>
      </el-col>
      <el-col :span="12">
        <el-tabs v-model="activeName2">
          <el-tab-pane label="字段权限" name="1">
            <div v-if="treeData.length>0" class="buttons">
              <el-button size="mini" @click="refreshData">刷 新</el-button>
              <el-button size="mini" @click="saveData">保 存</el-button>
              <el-button size="mini" @click="resetChecked">重 置</el-button>
              <el-tooltip placement="top" effect="light">
                <div slot="content">左侧表格多选选中，一次授权多个角色的字段
                </div>
                <el-button v-show="multipleDisabled" size="mini" type="primary" @click="allotHandler">分 配</el-button>
              </el-tooltip>
            </div>
            <el-tree
              ref="tree"
              v-loading="treeLoading"
              element-loading-text="拼命加载中..."
              element-loading-spinner="el-icon-loading"
              :data="treeData"
              show-checkbox
              :default-expand-all="expandAll"
              node-key="id"
              empty-text="暂无字段授权"
              :default-checked-keys="checkedArr"
              highlight-current
              :props="defaultProps"
            />
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  listRole
} from '@/api/system/role'
import {
  findAuthField,
  getRoleAuthField,
  saveRoleFieldAuth,
  saveMultipleRoleFieldAuth
} from '@/api/system/desform/onlineForm/onlCgformHead'
export default {
  name: 'OnlCgformRoleAuth',
  props: {
    dataId: {
      type: String,
      required: false,
      default: () => ''
    }
  },
  data() {
    return {
      roleTableData: [],
      treeLoading: false,
      loading: false,
      activeName1: '1',
      activeName2: '1',
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        roleName: undefined,
        roleKey: undefined,
        status: undefined
      },
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      treeData: [],
      expandAll: true,
      checkedArr: [], // 默认选中节点
      roleId: undefined, // 当前选中的角色id
      authMode: 'role', // 授权方式
      type: 'field', // 类型 字段 或者 按钮
      multipleSelection: [],
      multipleDisabled: false
    }
  },
  created() {
    this.getList()
    // this.refreshData()
  },
  methods: {
    /** 查询角色列表 */
    getList() {
      this.loading = true
      listRole(this.addDateRange(this.queryParams, this.dateRange)).then(
        response => {
          this.roleTableData = response.rows
          this.total = response.total
          this.loading = false
        }
      )
    },
    handleCurrentChange(row) {
      //  this.refreshData()
      this.treeLoading = true
      this.roleId = row.id
      const queryData = {
          roleId: row.id,
          headId: this.dataId,
          type: this.type
      }
      getRoleAuthField(queryData).then(res => {
          this.$refs.tree.setCheckedKeys([])
          this.checkedArr = res.data
          this.$refs.tree.setCheckedKeys(res.data)
          this.treeLoading = false
      })
    },
    resetChecked() {
      this.$refs.tree.setCheckedKeys([])
    },
    refreshData() {
       this.treeLoading = true
      findAuthField(this.dataId).then(res => {
        this.treeData = res.data
        this.treeLoading = false
      })
    },
    saveData() {
      if (!this.roleId) {
        this.$message.error('请选择左侧角色!')
        return
      }
      const checkedKeys = this.$refs.tree.getCheckedKeys()
      const filterCheckedKeys = []
      // TOOD 这里需要优化
      checkedKeys.map(key => {
        if (isNaN(key)) {
          filterCheckedKeys.push(key)
        }
      })
      // 封装提交的数据
      var submitData = {
          roleId: this.roleId,
          authMode: this.authMode,
          authIds: filterCheckedKeys,
          type: this.type,
          headId: this.dataId
        }
      saveRoleFieldAuth(submitData).then(res => {
        if (res.code === 200) {
            this.$message.success('分配成功!')
        }
      }).catch(() => {
           this.$message.error('分配失败!')
      })
    },
    allotHandler() {
      const checkedKeys = this.$refs.tree.getCheckedKeys()
      const filterCheckedKeys = []
      checkedKeys.map(key => {
        if (isNaN(key)) {
          filterCheckedKeys.push(key)
        }
      })
      const submitDataArr = []
      this.multipleSelection.forEach(item => {
          var submitData = {
          roleId: item,
          authMode: this.authMode,
          authIds: filterCheckedKeys,
          type: this.type,
          headId: this.dataId
        }
        submitDataArr.push(submitData)
      })
      saveMultipleRoleFieldAuth(submitDataArr).then(response => {
          if (response.code === 200) {
            this.$message.success('分配成功!')
        }
      }).catch(() => {
           this.$message.error('分配失败!')
      })
    },
    handleSelectionChange(val) {
      const ids = val.map(item => item.id)
      this.multipleSelection = ids
      this.multipleDisabled = (val.length > 0)
    }
  }
}
</script>

<style scoped>
.buttons {
  margin: 0px 0px 10px 0px;
}
</style>
